package com.atguigu.gmall.payment.service.impl;

import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Calendar;

/**
 * @author wk
 * @create 2021-09-14 18:32
 */
@Service
public class PaymentInfoServiceImpl implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;
    @Resource
    private PaymentInfoMapper paymentInfoMapper;

    // 支付表的相关信息
    @Override
    public PaymentInfo create(Long orderId, PaymentType paymentType) {
        // 避免幂等性问题
        // 1.先通过订单id查询订单信息是否已经存在
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>().eq("order_id", orderId));
        if (StringUtils.isEmpty(paymentInfo)) {
            // 如果为空 说明未下订单 创建订单
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
            paymentInfo = new PaymentInfo();
            paymentInfo.setOrderId(orderId);
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
            paymentInfo.setSubject(orderInfo.getTradeBody());
            paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setCreateTime(Calendar.getInstance().getTime());
            // 创建订单
            paymentInfoMapper.insert(paymentInfo);
        }
        return paymentInfo;
    }
}
